# encoding:utf-8

import os
import shutil
import logging
import string
from optparse import OptionParser
from _helpsvn import SvnHelper
from _helpgit import GitHelper



MODTEMPALTE_DESC = \
'''--{typekey}
'''

SINGTEMPALTE_DESC = '''Module "{packname}" "{packfile}"\n'''


class SquishBuild(object):
    '''use for auto-create the pack-lua file  '''
    
    _srcpath = None

    @staticmethod
    def _crt_cfg(typekey, pathlist, tag_):
        ret = ""
        ret = MODTEMPALTE_DESC.format(typekey=typekey)
        for fileobj in pathlist:
            abspath = fileobj[fileobj.find(tag_) + 1:]
            packname = abspath.replace("/", ".")[:-4]
            packpath = abspath
            newmod = SINGTEMPALTE_DESC.format(packname=packname, packfile=packpath)
            ret += newmod
        return ret


    @classmethod
    def _iter_default(cls, abspath):
        cfgpath = cls._srcpath + abspath
        cfglist = []
        for filename in os.listdir(cfgpath):
            fileobj = os.path.join(cfgpath, filename)
            if os.path.isfile(fileobj) and filename != ".DS_Store":
                cfglist.append(fileobj)
        ret = ""
        packname = abspath.split("/")[-1]
        ret += SquishBuild._crt_cfg(packname, cfglist, abspath)
        return ret
                
    @classmethod
    def _iter_stage(cls, stagepath, ignorefiles):
        stagepath = cls._srcpath + stagepath
        modlist = []
        otherlist = []
        scenelist = []
        viewlist = []
        winlist = []
        
        for filename in os.listdir(stagepath):
            fnum = ignorefiles.count(filename)
            fileobj = os.path.join(stagepath, filename)
            if os.path.isfile(fileobj) and fnum == 0:
                # win
                if filename.startswith("win"):
                    if filename == "winbase.lua":
                        winlist.insert(0, fileobj)
                    else:
                        winlist.append(fileobj)
                # view
                elif filename.startswith("view"):
                    if filename == "viewbase.lua":
                        viewlist.insert(0, fileobj)
                    else:
                        viewlist.append(fileobj)
                # scene
                elif filename.find("scene") != -1:
                    scenelist.append(fileobj)

                # other
                else:
                    otherlist.append(fileobj)
            else:
                # moddir
                if filename == "module":
                    for filename_ in os.listdir(fileobj):
                        fileobj_ = os.path.join(fileobj, filename_)
                        modlist.append(fileobj_)
        ret = ""
        ret += SquishBuild._crt_cfg("module", modlist, "/xlhall/stage")
        ret += SquishBuild._crt_cfg("scene", scenelist, "/xlhall/stage")
        ret += SquishBuild._crt_cfg("win", winlist, "/xlhall/stage")
        ret += SquishBuild._crt_cfg("view", viewlist, "/xlhall/stage")
        ret += SquishBuild._crt_cfg("other", otherlist, "/xlhall/stage")
        return ret

    @classmethod 
    def execute(cls, srcpath):
        cls._srcpath = srcpath
        stagecont = SquishBuild._iter_stage("/xlhall/stage", [".DS_Store", "testscene.lua"])
        cfgcont   = SquishBuild._iter_default("/xlhall/cfg")
        excont    = SquishBuild._iter_default("/xlhall/extend")
        modelcont = SquishBuild._iter_default("/xlhall/model")

        # auto generate
        fo = open("_auto_squishy", "r")
        oldcont = fo.read()
        fo.close()

        fr = open("squishy", "w")
        oldcont = oldcont.replace("${stage_generate}", stagecont) \
                            .replace("${cfgs}", cfgcont) \
                            .replace("${extend}", excont)\
                            .replace("${model}", modelcont)
        fr.write(oldcont)

        fr.close()


class SquishLua(object):
    '''使用squish打包脚本'''
    _svnhelper = None

    @classmethod
    def svn_commit(cls, tarpath):
        usr = "duanwenbin"
        pwd = "E6VFbB5o"
        cls._svnhelper = SvnHelper(usr, pwd)
        cls._svnhelper.svn_commit(tarpath, singlefile="../src/xlhall_pack.lua")

    @classmethod
    def svn_update(cls, tarpath):
        usr = "duanwenbin"
        pwd = "E6VFbB5o"
        cls._svnhelper = SvnHelper(usr, pwd)
        cls._svnhelper.svn_update(tarpath)

    @classmethod
    def excute(cls, srcpath, iszip=True):
        '''  
            执行
        '''
        os.chdir(srcpath)
        cls.svn_update(srcpath)

        SquishBuild.execute(srcpath)
        cmd_squ = "./squish {iszip}".format(
            iszip="" if iszip == "false"  else "--gzip")
        print ("excute the command->>>", cmd_squ)
        ret = os.popen(cmd_squ)
        cls.svn_commit(srcpath)

    @classmethod
    def excute_jenkin(cls, srcpath, iszip=True):
        os.chdir(srcpath)
        cls.svn_update(srcpath)
        SquishBuild.execute(srcpath)

        cmd_squ = "{luabin} ./squish {iszip}".format(
            luabin="/data0/tools/lua-5.1.5/src/lua",
            iszip="" if iszip == "false" else "--gzip")
        ret = os.popen(cmd_squ)
        cls.svn_commit(srcpath)
        

if __name__ == "__main__":
    print("======================================")
    print("==============SquishLua===============")
    print("======================================")

    DEBUG = True
    if DEBUG:
        srcpath = "/data0/public_work/xlhall/project/client/trunk/src_xlhall"
        isgzip = True
        SquishLua.excute_jenkin(srcpath, isgzip)
        import sys
        sys.exit()

    parser = OptionParser()
    parser.add_option("-s", "--src_path", dest="sppath",
                      default=None, help="Project's src path")

    parser.add_option("-g", "--gzip", dest="gzip",
                      default=True, help="If gzip the lua packfile.")

    (opts, args) = parser.parse_args()
    if (opts.sppath and opts.gzip):
        SquishLua.excute_jenkin(opts.sppath, opts.gzip)
